package grib2handler.bufr.http;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import grib2handler.bufr.save.SaveOriginal;
import grib2handler.grib.ftp.FTPLinkPool;
import grib2handler.util.FileUtil;
import org.apache.log4j.Logger;

public class HTTPDown {
	private final static Logger logger = Logger.getLogger(FTPLinkPool.class);
	/**
	 * 下载异常
	 */
	public final static int DOWN_ERROR = -1;
	/**
	 * 文件存在没有下载
	 */
	public final static int DOWN_NOTING = 0;
	/**
	 * 下载成功
	 */
	public final static int DOWN_SUCCESS = 1;
	
	/**
	 * 下载html代码
	 * 
	 * @param pageURL
	 * @param encoding
	 * @return
	 */
	public static String getHTML(String pageURL) {
		StringBuilder pageHTML = new StringBuilder();
		try {
			URL url = new URL(pageURL);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setConnectTimeout(10000);
			connection.setReadTimeout(30000);
			connection.setRequestProperty("User-Agent", "MSIE 7.0");
			BufferedReader br = new BufferedReader(new InputStreamReader(
					connection.getInputStream(), "utf-8"));
			String line = null;
			while ((line = br.readLine()) != null) {
				pageHTML.append(line);
				pageHTML.append("\r\n");
			}
			connection.disconnect();
		} catch (Exception e) {
			logger.info("url访问失败" + pageURL + e.getMessage());
		}
		return pageHTML.toString();
	}

	/**
	 * http下载
	 * 
	 * @param httpUrl
	 * @param saveFile
	 * @return
	 */
	public static int httpDownload(String httpUrl, String saveFile) {
		logger.info("开始下载" + httpUrl);
		// 创建目录
		FileUtil.creatParentPath(saveFile);

		// 下载网络文件
		int bytesum = 0;
		int byteread = 0;

		URL url = null;
		try {
			url = new URL(httpUrl);
		} catch (MalformedURLException e1) {
			logger.error("连接不存在" + httpUrl + e1.getMessage());
			return DOWN_ERROR;
		}
		FileOutputStream fs = null;
		try {
			URLConnection conn = url.openConnection();
			conn.setConnectTimeout(10000);
			conn.setReadTimeout(30000);
			//检查服务器文件大小
			int length = conn.getContentLength();
			//查看本地文件大小
			File f = new File(saveFile);
			if(f.exists() && f.length() >= length) {
				//本地文件存在不需要下载
				logger.info("本地文件存在， 无需下载" + httpUrl);
				return DOWN_NOTING;
			}
			InputStream inStream = conn.getInputStream();
			fs = new FileOutputStream(saveFile);

			byte[] buffer = new byte[1204];
			while ((byteread = inStream.read(buffer)) != -1) {
				bytesum += byteread;
				fs.write(buffer, 0, byteread);
			}
			//保存原始文件
			SaveOriginal.save(saveFile);
			logger.info("下载成功" + httpUrl + "大小：" + bytesum);
			return DOWN_SUCCESS;
		} catch (Exception e) {
			logger.error("下载失败" + httpUrl + e.getMessage());
			return DOWN_ERROR;
		} finally {
			if (fs != null) {
				try {
					fs.close();
				} catch (IOException e) {
					logger.error("连接关闭失败" + httpUrl + e.getMessage());
				}
			}
		}
	}
	
}
